package com.yanxi.user.web.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanxi.user.web.common.util.ManagedChannelUtils;
import com.yanxi.user.web.grpc.pullConfigService.PullConfigRequest;
import com.yanxi.user.web.grpc.pullConfigService.PullConfigResponse;
import com.yanxi.user.web.grpc.pullConfigService.PullConfigResponseOrBuilder;
import com.yanxi.user.web.grpc.pullConfigService.PullConfigServiceGrpc;
import io.grpc.ManagedChannel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.logging.Logger;

/**
 * 拉取配置
 */
public class PullConfigLoader implements EnvironmentPostProcessor {

    private static final String PROPERTY_SOURCE_NAME = "databaseProperties";

    /**
     * 拉取配置的时候 注册中心的 端口号 和 地址
     */
    private static final String regiservePort = "8090";

    private static final String regiserveUrl = "localhost";

    /**
     * 获取日志记录器
     */
    private static final Logger logger = Logger.getLogger(PullConfigLoader.class.getName());


    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

        logger.info("ServerConfig loading start");

        ManagedChannelUtils.runWithManagedChannel(regiserveUrl, regiservePort, channel -> {

            try {
                /**
                 * newBlockingStub 确保是同步调用
                 */
                PullConfigServiceGrpc.PullConfigServiceBlockingStub pullConfigServiceBlockingStub = PullConfigServiceGrpc.newBlockingStub(channel);
                /**
                 * 拉取配置
                 */
                PullConfigResponse response = pullConfigServiceBlockingStub.getConfigByTag(PullConfigRequest
                        .newBuilder()
                        .setStr("user")
                        .build());

                /**
                 * 调用成功
                 */
                if (response.getStatus() == 200) {

                    /**
                     * 类型转化
                     */
                    Map<String, Object> propertySource = JSON.parseObject(response.getData(), new TypeReference<Map<String, Object>>() {
                    });

                    /**
                     * 加载配置
                     */
                    environment.getPropertySources().addFirst(new MapPropertySource(PROPERTY_SOURCE_NAME, propertySource));

                    logger.info("ServerConfig loading Success");

                } else {

                    throw new Exception("ServerConfig return code error");

                }

            } catch (Exception e) {

                e.printStackTrace();

                logger.info("ServerConfig loading Exception");

            }

        });
    }
}
